﻿<%@ WebHandler Language="C#" Class="FileDownload" %>

using System;
using System.Web;
using System.IO;

public class FileDownload : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        try
        {
            string filePath = context.Request.QueryString["filePath"].ToString();

            FileStream fileStream = File.OpenRead(filePath);

            context.Response.ContentType = "application/octet-stream";
            context.Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
            context.Response.AddHeader("Content-Length", fileStream.Length.ToString());

            // 推送文件数据到客户端
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, bytesRead);
                context.Response.Flush();
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(ex.Message);
        }
    }


    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}